package com.web.surf.sample.eshop.faces.navigation;

import javax.faces.component.UICommand;
import javax.faces.event.ActionEvent;

import com.web.surf.sample.eshop.faces.backing.beans.DataPager;

/**
 * Class that realize Pager's crossing from page to page
 * 
 * @author SavenkoNV
 */
public class PagerNumberNavigator {

	private Integer[] pages;
	private int pageRange = 5;

	private DataPager pager;

	/**
	 * Creates pages for introducing on JSF page
	 */
	private void createPages() {
		int totalPages = pager.getTotalPages();
		int pagesLength = Math.min(pageRange, totalPages);
		pages = new Integer[pagesLength];
		// firstPage must be greater than 0 and lesser than
		// totalPages-pagesLength.
		int firstPage = Math.min(Math.max(0, pager.getCurrentPage()
				- (pageRange / 2)), totalPages - pagesLength);
		// Create pages (page numbers for page links).
		for (int i = 0; i < pagesLength; i++) {
			pages[i] = ++firstPage;
		}
	}

	public Integer[] getPages() {
		createPages();
		return pages;
	}

	public void page(ActionEvent event) {
		int touchedPage = (Integer) ((UICommand) event.getComponent())
				.getValue();
		pager.setCurrentPage(touchedPage);
		pager.setFirstRow((touchedPage - 1) * pager.getRowsPerPage());
		pager.executeNavigation(pager.getFirstRow());
	}

	public void renew(ActionEvent event) {
		pager.setCurrentPage(1);
		pager.setFirstRow(0);
		createPages();
		pager.executeNavigation(pager.getFirstRow());
	}

	public int getPageRange() {
		return pageRange;
	}

	// Setter for configuring page range
	public void setPageRange(int pageRange) {
		this.pageRange = pageRange;
	}

	// Spring setter
	public void setPager(DataPager pager) {
		this.pager = pager;
	}
}